package com.winning.sx.microframework.controller.base;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.dapi.data.entity.DataTable;
import com.winning.sx.microframework.common.util.Constains;
import com.winning.sx.microframework.common.util.FileTools;
import com.winning.sx.microframework.common.util.FlowCodeUtil;
import com.winning.sx.microframework.common.util.SqlTool;
import com.winning.sx.microframework.controller.sysmanage.LoginController;
import com.winning.sx.microframework.model.manage.LoginSession;
import com.winning.sx.microframework.model.message.AjaxDataResponseMessage;
import com.winning.sx.microframework.model.message.AjaxTableResponseMessage;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.base.EquipmentService;
import com.winning.sx.microframework.service.base.MessageService;
import com.winning.sx.microframework.service.base.SearchService;
import com.winning.sx.microframework.service.sysmanage.ConstService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/interface")
public class InterfaceController {
    @Autowired
    EasyService easyService;
    @Autowired
    SearchService searchService;
    @Autowired
    MessageService messageService;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    ConstService constService;
    private static final Logger logger = LoggerFactory.getLogger(InterfaceController.class);

    @ResponseBody
    @RequestMapping(value = {"/queryPersonInformation"})
    public AjaxDataResponseMessage queryPersonInformation(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if (login == null || login.getStaffId() == 0) {
                //未认证用户
                List reList = new ArrayList();
                Map reMap = new HashMap();
                reList.add(reMap);
                reMap.put("staffId", "0");
                reMap.put("cRoleId", "0");
                reMap.put("name", "未认证用户");
                reMap.put("organizationName", "未认证");
                reMap.put("organizationNameSon", "");
                reMap.put("job", "");
                reMap.put("organizationType", "");
                reMap.put("cRoleName", "未认证");
                ajaxDataResponseMessage.setData(reList);
                ajaxDataResponseMessage.setSuccess(true);
                return ajaxDataResponseMessage;
            }
            Map map = new HashMap();
            map.put("id", login.getStaffId().toString());
            String sql = "  select s.organizationId, s.id staffId,s.name,r.cRoleId,r.cRoleName,o1.name organizationName,o.name organizationNameSon,s.job,c.name organizationType" +
                    " from BASE_Staff s " +
                    "  left join BASE_Organization o on s.organizationId=o.id " +
                    "  left join BASE_Organization o1 on o.superOrganizationId=o1.id " +
                    "  left join PM_ROLES r on r.cRoleID=s.role " +
                    "  left join BASE_Const c on c.code=o.organizationType " +
                    " where s.id=:id";
            DataTable all = easyService.querySql(sql, map);
            ajaxDataResponseMessage.setData(all.getDataRows());
            ajaxDataResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/saveUserInformation"})
    public AjaxDataResponseMessage saveUserInformation(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            param.put("id", login.getStaffId().toString());
            easyService.save("BASE_Staff", "id", param);
            ajaxDataResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/getMyWarehouse"})
    public AjaxTableResponseMessage getMyWarehouse(String datas) {
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        AjaxTableResponseMessage ajaxDataResponseMessage = new AjaxTableResponseMessage();
        try {
            String sql = "  select w.* from BASE_Warehouse w left join BASE_WarehouseStaff s on w.id=s.warehouseId and s.validFlag='100001' " +
                    " where w.validFlag='100001' and s.staffId=:id";
            switch (login.getRoleId()) {
                case "1":
                    sql = "  select w.* from BASE_Warehouse w " +
                            " where w.validFlag='100001' ";
                    break;
                case "2":
                    sql = "  select w.* from BASE_Warehouse w " +
                            " where w.validFlag='100001' ";
                    break;
            }
            Map map = new HashMap();
            map.put("id", login.getStaffId().toString());
            DataTable all = easyService.querySql(sql, map);
            ajaxDataResponseMessage.setDatas(all.getDataRows());
            ajaxDataResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/queryWarehouseChangeReport"})
    public AjaxTableResponseMessage queryWarehouseChangeReport(String datas) {
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        AjaxTableResponseMessage ajaxDataResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            if (param.get("startDate") == null || param.get("endDate") == null || param.get("warehouseId") == null) {
                throw new Exception("参数不完整");
            }
            String sql = " SELECT " +
                    "  wd.warehouseId,   e.name eName, " +
                    "  cs.name brandName," +
                    "  eq.name, " +
                    "  wd.count                     countNow, " +
                    "  (select sum(count) from BUSI_WarehouseChange c1 " +
                    "           where c1.warehouseId = wd.warehouseId AND c1.type LIKE '3330%' AND c1.validFlag = '100001' AND " +
                    "                 c1.state = '334002' AND c1.modelId = wd.equipmentId " +
                    "                  AND c1.updateTime >= :startDate + ' 00:00:00' AND c1.updateTime <= :endDate + ' 23:59:59' " +
                    "            )                countAdd, " +
                    "        (select sum(count) from BUSI_WarehouseChange c1 " +
                    "           where c1.warehouseId = wd.warehouseId AND c1.type LIKE '3331%' AND c1.validFlag = '100001' AND " +
                    "                 c1.state = '334002' AND c1.modelId = wd.equipmentId " +
                    "                   AND c1.updateTime >= :startDate + ' 00:00:00' AND c1.updateTime <= :endDate + ' 23:59:59' " +
                    "            )                  countMinus," +
                    "  (SELECT TOP 1 CASE WHEN substring(c.type, 0, 5) = '3330' " +
                    "    THEN c.beforeCount + c.count " +
                    "                ELSE c.beforeCount - c.count END " +
                    "   FROM BUSI_WarehouseChange c " +
                    "   WHERE " +
                    "     c.state = '334002' AND c.validFlag = '100001' AND c.warehouseId = wd.warehouseId AND c.modelId = wd.equipmentId " +
                    "     AND c.updateTime <= :endDate+' 23:59:59' " +
                    "   ORDER BY c.updateTime DESC) endCount " +
                    "FROM BASE_WarehouseDetail wd " +
                    "  LEFT JOIN BASE_EquipmentDetail e ON wd.equipmentId = e.id " +
                    "  LEFT JOIN BASE_EqClass eq ON e.type = eq.code " +
                    "   left join BASE_Const cs on cs.code=e.brand " +

                    " where wd.validFlag='100001' and wd.warehouseId=:warehouseId " +
                    "GROUP BY wd.warehouseId, eq.name, wd.count, wd.equipmentId,e.name,  cs.name ";
            DataTable all = easyService.querySql(sql, param);
            ajaxDataResponseMessage.setDatas(all.getDataRows());
            ajaxDataResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }


    @ResponseBody
    @RequestMapping(value = {"/logOut"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage logOut(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if (login.getStaffId() == 0) {
                //未认证用户
                Subject subject = SecurityUtils.getSubject();
                subject.logout();
                ajaxDataResponseMessage.setSuccess(true);
                return ajaxDataResponseMessage;
            } else {
                Map deleteParam = new HashMap();
                deleteParam.put("openId", login.getcUserOpenId());
                easyService.delete("PM_StaffWeChat", "openId", deleteParam);
                Subject subject = SecurityUtils.getSubject();
                subject.logout();
                ajaxDataResponseMessage.setSuccess(true);
                return ajaxDataResponseMessage;
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    //查询总数量
    @ResponseBody
    @RequestMapping(value = {"/queryEquipmentTotal"})
    public AjaxTableResponseMessage queryEquipmentTotal(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            param.put("orgId", login.getOrgId());
            // 分两种，如果是中心管理员，那么查询所有的，如果是客户管理员，那么查询部分的，维修人员看不到
            //1：超管2：中心管理3：客户管理4：使用5：维修0:未认证
            String sql = "";
            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select count(e.id) totalNum from BASE_Equipment e where validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        (param.get("state") != null ? " and state=:state " : "");
            } else if (login.getRoleId().equals("3")) {
                sql = "  select count(e.id) totalNum from BASE_Equipment e  where validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        (param.get("state") != null ? " and state=:state " : "") +
                        " and  e.organizationId in(" +
                        " select id from BASE_Organization o where o.id=:orgId or o.superOrganizationId=:orgId" +
                        ")";
            } else {
                sql = "  select 0 totalNum ";
            }

            DataTable all = easyService.querySql(sql, param);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/queryEquipmentType"})
    public AjaxTableResponseMessage queryEquipmentType(String datas) {
        AjaxTableResponseMessage ajaxDataResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            Map map = new HashMap();
            map.put("orgId", login.getOrgId());
            map.put("state", param.get("state").toString());
            map.put("staffId", login.getStaffId().toString());
            String sql = "";
            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select  count(e.id) totalNum,c.name type,c.code code from BASE_Equipment e " +
                        " left join BASE_EqClass c on c.code=e.oneCode " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" + " and e.state in (" + param.get("state").toString() + ")" +
                        " group by c.name,c.code order by c.code";
            } else {
                sql = "  select  count(e.id) totalNum,eq.name type,eq.code code from BASE_Equipment e " +
                        " left join BASE_EqClass eq on eq.code=e.oneCode " +
                        " left join BUSI_WarehouseChange c on e.changeId=c.id " +
                        "  left join BUSI_EquipmentGet g on c.getId=g.id" +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" + " and e.state in (" + param.get("state").toString() + ")" +
                        " and  g.useStaffId=:staffId" +
                        " group by eq.name,eq.code order by eq.code";
            }
            DataTable all = easyService.querySql(sql, map);
            ajaxDataResponseMessage.setDatas(all.getDataRows());
            ajaxDataResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    //我的所属机构下的资产按类型查询得到分组总数
    @ResponseBody
    @RequestMapping(value = {"/queryEquipmentBrand"})
    public AjaxTableResponseMessage queryEquipmentBrand(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            Map map = new HashMap();
            map.put("orgId", login.getOrgId());
            map.put("code", param.get("code").toString());
            map.put("staffId", login.getStaffId().toString());
            String sql = "";
            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select  count(e.id) num,e.name brand, sum(t.mcount) mcount  from BASE_Equipment e " +
                        " left join BASE_EqClass c on c.code=e.oneCode " +
                        " left join ( " +
                        "  select a.equipmentId, count(id) mcount from BUSI_MaintenanceApplication a  where a.state in (201601,201602,201621,201622,201623) group by a.equipmentId " +
                        "  ) t on e.id=t.equipmentId" +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" + " and e.state in (" + param.get("state").toString() + ")" +
                        " and  e.oneCode =:code" +
                        " group by e.name";
            } else {
                sql = "  select  count(e.id) num,e.name brand , sum(t.mcount) mcount  from BASE_Equipment e " +
                        " left join BASE_EqClass eq on eq.code=e.oneCode " +
                        " left join ( " +
                        "  select a.equipmentId, count(id) mcount from BUSI_MaintenanceApplication a  where a.state in (201601,201602,201621,201622,201623) group by a.equipmentId " +
                        "  ) t on e.id=t.equipmentId" +
                        " left join BUSI_WarehouseChange c on e.changeId=c.id " +
                        "  left join BUSI_EquipmentGet g on c.getId=g.id" +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" + " and e.state in (" + param.get("state").toString() + ")" +
                        " and  g.useStaffId=:staffId" +
                        " and  e.oneCode =:code" +
                        " and  e.organizationId in(" +
                        " select id from BASE_Organization o where o.id=:orgId or o.superOrganizationId=:orgId" +
                        ")" +
                        " group by e.name ";
            }


            DataTable all = easyService.querySql(sql, map);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //查询资产列表
    @ResponseBody
    @RequestMapping(value = {"/queryEquipmentList"})
    public AjaxTableResponseMessage queryEquipmentList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            param.put("orgId", login.getOrgId());
            param.put("superOrganizationId", login.getOrgId());
            param.put("organizationType", "400001");
            Map myOrg = constService.queryMyOrg(param);
            param.put("staffId", login.getStaffId().toString());
            // 分两种，如果是中心管理员，那么查询所有的，如果是客户管理员，那么查询部分的，维修人员看不到
            //1：超管2：中心管理3：客户管理4：使用5：维修0:未认证
            String sql = "";
            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select (select count(id) from BUSI_MaintenanceApplication a where  a.equipmentId=e.id and a.state in (201601,201602,201621,201622,201623)) mcount,e.*,case when op.id is null then o.name else op.name+'-'+o.name end orgName,q.code QRcodeName from BASE_Equipment e " +
                        " left join BASE_Organization o on e.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " left join BASE_QRcode q on q.id=e.QRCode " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" + " and e.state in (" + param.get("state").toString() + ")" +
                        (param.get("searchKey") != null ? " and (q.code like :searchKey+'%' or e.barCode like :searchKey+'%')" : "") +
                        (param.get("oneCode") != null ? " and e.oneCode=:oneCode" : "") +
                        (param.get("brandCode") != null ? " and e.brandCode=:brandCode" : "") +
                        " order by e.createTime desc";
            } else {
                sql = "  select (select count(id) from BUSI_MaintenanceApplication a where  a.equipmentId=e.id and a.state in (201601,201602,201621,201622,201623)) mcount,e.*,case when op.id is null then o.name else op.name+'-'+o.name end orgName,q.code QRcodeName from BASE_Equipment e " +
                        " left join BASE_Organization o on e.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " left join BASE_QRcode q on q.id=e.QRCode " +
                        " left join BUSI_WarehouseChange c on e.changeId=c.id " +
                        "  left join BUSI_EquipmentGet g on c.getId=g.id" +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" + " and e.state in (" + param.get("state").toString() + ")" +
                        " and  g.useStaffId=:staffId" +
                        (param.get("oneCode") != null ? " and e.oneCode=:oneCode" : "") +
                        (param.get("searchKey") != null ? " and (q.code like :searchKey+'%' or e.barCode like :searchKey+'%')" : "") +
                        (param.get("brandCode") != null ? " and e.brandCode=:brandCode" : "") +
                        " order by e.createTime desc";
            }

            DataTable all = easyService.querySql(sql, param);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //查询资产的维修统计
    @ResponseBody
    @RequestMapping(value = {"/analysisMaintenance"})
    public AjaxDataResponseMessage analysisMaintenance(String datas) {
        AjaxDataResponseMessage ajaxTableResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map result = new HashMap();

            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            param.put("orgId", login.getOrgId());
            param.put("staffId", login.getStaffId().toString());
            // 分两种，如果是中心管理员，那么查询所有的，如果是客户管理员，那么查询部分的，维修人员看不到
            //1：超管2：中心管理3：客户管理4：使用5：维修0:未认证
            String sql = "";
            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select  count(e.id) num,e.name brand, isnull(sum(t.mcount),0) mcount  from BASE_Equipment e " +
                        " left join BASE_EqClass c on c.code=e.oneCode " +
                        " left join ( " +
                        "  select a.equipmentId, count(id) mcount from BUSI_MaintenanceApplication a  where a.state in (201601,201602,201621,201622,201623) group by a.equipmentId " +
                        "  ) t on e.id=t.equipmentId" +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " group by e.name order by mcount desc ";
            } else {
                sql = "  select  count(e.id) num,e.name brand , isnull(sum(t.mcount),0) mcount  from BASE_Equipment e " +
                        // " left join BASE_EqClass eq on eq.code=e.oneCode " +
                        " left join ( " +
                        "  select a.equipmentId, count(id) mcount from BUSI_MaintenanceApplication a  where a.state in (201601,201602,201621,201622,201623) group by a.equipmentId " +
                        "  ) t on e.id=t.equipmentId" +
                        " left join BUSI_WarehouseChange c on e.changeId=c.id " +
                        "  left join BUSI_EquipmentGet g on c.getId=g.id" +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and  g.useStaffId=:staffId" +
                        " group by e.name order by mcount desc ";
            }
            DataTable all1 = easyService.querySql(sql, param);
            result.put("xh", all1.getDataRows());//型号

            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select top 10  c.name maintenanceResult, isnull(count(a.id),0) mcount  from BASE_Equipment e " +
                        " left join BUSI_MaintenanceApplication a on a.state in (201601,201602,201621,201622,201623) and a.equipmentId=e.id" +
                        " left join BASE_Const c on c.code=a.maintenanceResult " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " group by c.name order by c.name ";
            } else {
                sql = "  select top 10 cr.name maintenanceResult, isnull(count(a.id),0) mcount  from BASE_Equipment e " +
                        " left join BUSI_MaintenanceApplication a on a.state in (201601,201602,201621,201622,201623) and a.equipmentId=e.id" +
                        " left join BASE_Const cr on cr.code=a.maintenanceResult " +
                        " left join BUSI_WarehouseChange c on e.changeId=c.id " +
                        "  left join BUSI_EquipmentGet g on c.getId=g.id" +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and  g.useStaffId=:staffId" +
                        " group by cr.name order by cr.name ";
            }
            DataTable all2 = easyService.querySql(sql, param);
            result.put("fs", all2.getDataRows());//方式

            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select top 10 e.name,e.usePosition,q.code QRCode,isnull(count(a.id),0) mcount  from BASE_Equipment e " +
                        " left join BASE_QRcode q on e.QRCode=q.id " +
                        " left join BUSI_MaintenanceApplication a  on a.state in (201601,201602,201621,201622,201623) and e.id=a.equipmentId " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " group by e.name,e.usePosition,q.code  order by mcount desc ";
            } else {
                sql = "  select top 10 e.name,e.usePosition,q.code QRCode,isnull(count(a.id),0) mcount  from BASE_Equipment e " +
                        " left join BASE_QRcode q on e.QRCode=q.id " +
                        " left join BUSI_MaintenanceApplication a  on a.state in (201601,201602,201621,201622,201623) and e.id=a.equipmentId " +
                        " left join BUSI_WarehouseChange c on e.changeId=c.id " +
                        "  left join BUSI_EquipmentGet g on c.getId=g.id" +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and  g.useStaffId=:staffId" +
                        " group by e.name,e.usePosition,q.code order by mcount desc ";
            }
            DataTable all3 = easyService.querySql(sql, param);

            result.put("zq", all3.getDataRows());//资产
            ajaxTableResponseMessage.setData(result);
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    private void secretMap(Map map, int level, String key) {
        try {
            if (map.get(key) == null) return;
            String value = map.get(key).toString();
            switch (level) {
                case 0:
                    if (value.length() > 4) value = "*******" + value.substring(value.length() - 4);
                    map.put(key, value);
                    break;
                case 1:
                    map.put(key, "*******");
                    break;
                case 2:
                    map.remove(key);
                    break;
                default:
                    map.put(key, "*******");
                    break;
            }
        } catch (Exception e) {
            logger.error("secretMap" + key, e);
            e.printStackTrace();
        }
    }
    //我的所属机构下的资产按类型查询得到明细

    @ResponseBody
    @RequestMapping(value = {"/queryEquipmentManageDetail"})
    public AjaxTableResponseMessage queryEquipmentManageDetail(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            String sql = "  select c1.name brand ,e.model,e.usePosition,e.createTime,e.barCode,q.code QRCode,count(h.id) repairSuccessCount from BASE_Equipment e " +
                    "left join BUSI_MaintenanceApplication m on m.equipmentId=e.id " +
                    "left join BUSI_handleResult h on h.equipmentId=m.id and h.maintenanceResult='800001' " +
                    "left join BASE_Const c1 on c1.code=e.brandCode  " +
                    "left join BASE_QRcode q on q.id=e.QRCode " +
                    "where 1=1 " +
                    (param.get("code") != null ? (" and e.oneCode='" + param.get("code") + "'") : "") +
                    " group by c1.name,e.model,e.usePosition,e.createTime,e.barCode,q.code";
            DataTable all = easyService.querySql(sql, param);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }
    // 资产查询得到明细-二维码扫码接口

    @ResponseBody
    @RequestMapping(value = {"/queryEquipmentDetail"})
    public AjaxDataResponseMessage queryEquipmentDetail(String datas) {
        AjaxDataResponseMessage ajaxTableResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            else {
                ajaxTableResponseMessage.setSuccess(false);
                ajaxTableResponseMessage.setErrorMsg("二维码不能为空");
                return ajaxTableResponseMessage;
            }
            String sql = "select eg.useStaffId,eg.useType, wc.flowCode changeCode,wc.warehouseId,wc.type changeType,ed.image modelImage, " +
                    " e.*,s2.name useStaffName,o.name organizationName," +
                    " c.name type,co.name brand,q.code QRcode,s.name createName,s1.name updateName,e.model model  from BASE_Equipment e " +

                    "left join BASE_EquipmentDetail ed on ed.id=e.modelId " +
                    "left join BASE_Organization o on o.id=e.organizationId " +
                    "left join BASE_Const c on c.code =e.oneCode  " +
                    "left join BASE_Const co on co.code=e.brandCode " +

                    "left join BUSI_WarehouseChange wc on wc.id =e.changeId  " +
                    "left join BUSI_EquipmentGetDetail egd on wc.getDetailId =egd.id  " +
                    "left join BUSI_EquipmentGet eg on egd.getId =eg.id  " +
                    "left join BASE_Staff s2 on s2.id=eg.useStaffId " +

                    "left join BASE_Staff s on s.id=e.inputStaffId " +
                    "left join BASE_Staff s1 on s1.id=e.updateStaffId " +
                    "  left join BASE_QRcode q on q.id=e.QRCode " +
//                    "  select e.*,o.name orgName,s.name,g.useType,cs.name useTypeName,q.code QRcodeName,c.updateTime useTime from BASE_Equipment e " +
//                    "  left join BASE_QRcode q on q.id=e.QRCode " +
//                    " left join BUSI_WarehouseChange c on e.changeId=c.id " +
//                    "  left join BUSI_EquipmentGet g on c.getId=g.id " +
//                    " left join BASE_Organization o on g.useOrgId=o.id " +
//                    " left join BASE_Staff s on g.useStaffId=s.id " +
//                    " left join BASE_Const cs on cs.code=g.useType" +
                    " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' and q.code=:QRcode";
            DataTable all = easyService.querySql(sql, param);
            Map ret = new HashMap();
            if (all.getDataRows().size() != 1) {
                if (login == null) {
                    throw new NullPointerException();
                } else if (login.getRoleId().equals("0")) {
                    ajaxTableResponseMessage.setSuccess(false);
                    ajaxTableResponseMessage.setErrorMsg("0-非法二维码！");
                    return ajaxTableResponseMessage;
                } else {
                    Map QRCode = new HashMap();
                    Map QRParam = new HashMap();
                    QRParam.put("code", param.get("QRcode"));
                    QRCode = easyService.queryEntity("BASE_QRcode", QRParam);
                    if (QRCode == null) {
                        ajaxTableResponseMessage.setSuccess(false);
                        ajaxTableResponseMessage.setErrorMsg("1-非法二维码！");
                        return ajaxTableResponseMessage;
                    } else {
                        ajaxTableResponseMessage.setSuccess(true);
                        Map initData = new HashMap();
                        initData.put("QRCode", QRCode.get("id"));
                        initData.put("organizationId", login.getOrgId());
                        ajaxTableResponseMessage.setData(initData);
                        ajaxTableResponseMessage.setErrorMsg("notActive");
                        return ajaxTableResponseMessage;
                    }
                }
            } else {
                Map Equipment = all.getDataRows().get(0);
                ret.put("Equipment", Equipment);
                //这里根据密保等级进行部分数据处理
                if (login == null || !login.getRoleId().equals("0")) {//管理员可以查阅信息，否则影响编辑内容
                    if (Equipment.get("secrecy").equals(Constains.SECRET_ONE)) {
                        secretMap(Equipment, 0, "organizationName");
                        secretMap(Equipment, 0, "usePosition");
                        secretMap(Equipment, 0, "buyTime");
                    } else if (Equipment.get("secrecy").equals(Constains.SECRET_TWO)) {
                        secretMap(Equipment, 1, "organizationName");
                        secretMap(Equipment, 1, "usePosition");
                        secretMap(Equipment, 1, "buyTime");
                    } else if (Equipment.get("secrecy").equals(Constains.SECRET_THREE)) {
                        secretMap(Equipment, 2, "organizationName");
                        secretMap(Equipment, 2, "usePosition");
                        secretMap(Equipment, 2, "buyTime");
                        secretMap(Equipment, 2, "configurationDescription");
                        secretMap(Equipment, 2, "barCode");
                        secretMap(Equipment, 2, "brand");
                        secretMap(Equipment, 2, "updateName");
                        secretMap(Equipment, 2, "createName");
                        secretMap(Equipment, 2, "nameplatePhoto");
                        secretMap(Equipment, 2, "externalPhotos");
                        secretMap(Equipment, 2, "modelImage");
                        secretMap(Equipment, 2, "changeCode");
                        secretMap(Equipment, 2, "useStaffName");
                        secretMap(Equipment, 1, "name");
                        secretMap(Equipment, 2, "model");
                    }
                }
                if (Equipment.get("state").equals(Constains.Equipment_state_Repair) && login != null && login.getStaffId() != 0) {
                    //维修中 查询维修信息
                    sql = "  select top 1 e.*,s.name ApplyName,c.name questionTypeName from BUSI_MaintenanceApplication e  " +
                            "  left join BASE_Staff s on e.applyStaffId=s.id " +
                            "  left join  BASE_Const c on c.code=e.questionTypeCode" +
                            " where  e.validFlag='100001' and e.equipmentId=" + Equipment.get("id").toString() + " order by e.createTime desc";
                    Map MaintenanceApplication = easyService.querySql(sql, param).getDataRows().get(0);
                    ret.put("MaintenanceApplication", MaintenanceApplication);

                    Map temp = new HashMap();
                    temp.put("id", MaintenanceApplication.get("id").toString());
                    //获取维修提交记录
                    sql = "select r.*,c.name submitName,s.telephone,s.name repairName from BUSI_RepairSubmitRecord r " +
                            "  left join BASE_Const c on c.code=r.submitType " +
                            "  left join BASE_Staff s on s.id=r.toStaffId " +
                            " where r.state='" + Constains.RepairSubmit_OK + "' and r.repairApplyId=:id order by r.createTime";
                    DataTable submit = easyService.querySql(sql, temp);
                    if (submit.getTotalRowNum() > 0)
                        ret.put("submitRecord", submit.getDataRows().get(0));

                    //获取维修附件记录
                    sql = "select r.* from BUSI_RepairSupplement r " +
                            " where r.repairApplyId=:id order by r.createTime";
                    DataTable supplement = easyService.querySql(sql, temp);
                    ret.put("supplement", supplement.getDataRows());

                }
                //如果资产状态是未确认信息
                if (Equipment.get("state").equals(Constains.Equipment_state_edit)) {
                    //获取维修附件记录
                    sql = "select r.* from BUSI_EquipmentChange r " +
                            " where r.eId='" + Equipment.get("id").toString() + "' and type='123009' and validFlag='100001' and state in ('334003') order by r.createTime desc";
                    DataTable changeInfo = easyService.querySql(sql, new HashMap<>());
                    if (changeInfo.getTotalRowNum() > 0) {
                        ret.put("changeInfo", changeInfo.getDataRows().get(0));
                    }
                }
                if (param.get("flowCode") != null) {
                    //维修中 查询维修信息
                    sql = "  select top 1 e.*,s.name ApplyName,c.name questionTypeName from BUSI_MaintenanceApplication e  " +
                            "  left join BASE_Staff s on e.applyStaffId=s.id " +
                            "  left join  BASE_Const c on c.code=e.questionTypeCode" +
                            " where  e.validFlag='100001' and e.flowCode=" + param.get("flowCode").toString();
                    Map MaintenanceApplication = easyService.querySql(sql, param).getDataRows().get(0);
                    ret.put("MaintenanceApplication", MaintenanceApplication);

                    Map temp = new HashMap();
                    temp.put("id", MaintenanceApplication.get("id").toString());
                    //获取维修提交记录
                    sql = "select r.*,c.name submitName,s.telephone,s.name repairName from BUSI_RepairSubmitRecord r " +
                            "  left join BASE_Const c on c.code=r.submitType " +
                            "  left join BASE_Staff s on s.id=r.toStaffId " +
                            " where r.state='" + Constains.RepairSubmit_OK + "' and r.repairApplyId=:id order by r.createTime desc";
                    DataTable submit = easyService.querySql(sql, temp);
                    if (submit.getTotalRowNum() > 0)
                        ret.put("submitRecord", submit.getDataRows().get(0));

                    //获取维修附件记录
                    sql = "select r.* from BUSI_RepairSupplement r " +
                            " where r.repairApplyId=:id order by r.createTime";
                    DataTable supplement = easyService.querySql(sql, temp);
                    ret.put("supplement", supplement.getDataRows());

                }
                if(Equipment.get("model")!=null) {
                    //获取产品介绍信息
                    sql = "select code from BASE_Product r where r.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' and r.brandCode=:brandCode and r.modelCode=:modelCode";
                    Map pro = new HashMap();
                    pro.put("brandCode", Equipment.get("brandCode").toString());
                    pro.put("modelCode", Equipment.get("model").toString());
                    DataTable product = easyService.querySql(sql, pro);
                    ret.put("product", product.getDataRows());
                }
            }
            ajaxTableResponseMessage.setData(ret);
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            logger.error("系统异常", e);
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //维修中数量 弃用
    @ResponseBody
    @RequestMapping(value = {"/maintenance"})
    public AjaxTableResponseMessage queryMaintenance(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            Map map = new HashMap();
            map.put("id", login.getStaffId().toString());

            Map entity = easyService.queryEntity("BASE_Staff", map);
            Map paramNew = new HashMap();
            paramNew.put("orgId", login.getOrgId());
            paramNew.put("telephone", login.getcUserTelephone());
            paramNew.put("staffId", login.getStaffId().toString());
            if (entity.size() > 0) {
                paramNew.put("telephone", entity.get("telephone"));
                String role = entity.get("role").toString();
                login.setRoleId(role);
            }
            //1：超管2：中心管理3：客户管理4：使用5：维修 0:未认证
            String sql = "";
            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select count(e.id) totalNum from BUSI_MaintenanceApplication e where validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and state in ('201201','201202','201203','201301','201302','201402','201501','201502')";
            } else if (login.getRoleId().equals("3")) {
                sql = "  select count(e.id) totalNum from BUSI_MaintenanceApplication e " +
                        " left join BASE_Equipment q on e.equipmentId=q.id " +
                        "  where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and e.state in ('201201','201202','201203','201301','201302','201402','201501','201502')" +
                        " and  q.organizationId in(" +
                        " select id from BASE_Organization o where o.id=:orgId or o.superOrganizationId=:orgId" +
                        ")";
            } else if (login.getRoleId().equals("4") || login.getRoleId().equals("0")) {
                sql = "  select count(e.id) totalNum from BUSI_MaintenanceApplication e where validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and (applyStaffId =:staffId or telephone=:telephone)" +
                        " and state in ('201201','201202','201203','201301','201302','201402','201501','201502')";
            } else if (login.getRoleId().equals("5")) {
                sql = "  select count(e.id) totalNum from BUSI_MaintenanceApplication e " +
                        " where validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and (select top 1 toStaffId from BUSI_RepairSubmitRecord s where e.id=s.repairApplyId and validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' and state='" + Constains.RepairSubmit_OK + "' order by createTime desc )=:staffId" +
                        " and state in ('201501')";
            }
            DataTable all = easyService.querySql(sql, paramNew);

            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //我的维修申请
    @ResponseBody
    @RequestMapping(value = {"/myMain"})
    public AjaxTableResponseMessage myMaintenance(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            param.put("applyStaffId", login.getStaffId().toString());
            String sqlPlus = "";
            if (login.getStaffId().toString().equals("0")) {
                sqlPlus = " and ( e.telephone='" + login.getcUserTelephone() + "' " +
                        ((login.getcUserOpenId() == null || "".equals(login.getcUserOpenId()) || "null".equals(login.getcUserOpenId())) ? ")" : " or e.openId='" + login.getcUserOpenId() + "')");
            } else {
                sqlPlus = " and ( e.applyStaffId='" + login.getStaffId() + "'" +
                        ((login.getcUserOpenId() == null || "".equals(login.getcUserOpenId()) || "null".equals(login.getcUserOpenId())) ? ")" : " or e.openId='" + login.getcUserOpenId() + "')");
            }
            String sql = "  select e.*,b.name,b.oneCode eType,o.name orgName,b.usePosition,c.name questionTypeName" +
                    " from BUSI_MaintenanceApplication e " +
                    " left join  BASE_Equipment b on b.id=e.equipmentId" +
                    " left join  BASE_Const c on c.code=e.questionTypeCode" +
                    " left join  BASE_Organization o on b.organizationId =o.id " +
                    " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' " +
                    sqlPlus +
                    " and e.state in (" + param.get("state") + ") order by e.createTime desc";

            //维修中：'201201','201202','201203','201301','201302','201402','201501','201502'
            //其他
            DataTable all = easyService.querySql(sql, param);

            for (int i = 0; i < all.getDataRows().size(); i++) {
                Map row = all.getDataRows().get(i);
                Map temp = new HashMap();
                temp.put("id", row.get("id").toString());
                //获取维修提交记录 找维修工
                sql = "select r.*,c.name submitName,s.telephone from BUSI_RepairSubmitRecord r " +
                        "  left join BASE_Const c on c.code=r.submitType " +
                        "  left join BASE_Staff s on s.id=r.toStaffId " +
                        " where r.state='" + Constains.RepairSubmit_OK + "' and r.repairApplyId=:id order by r.createTime";

                DataTable submit = easyService.querySql(sql, temp);
                row.put("submitRecord", submit.getDataRows());

                //获取维修附件记录
                sql = "select r.* from BUSI_RepairSupplement r " +
                        " where r.repairApplyId=:id order by r.createTime";
                DataTable supplement = easyService.querySql(sql, temp);
                row.put("supplement", supplement.getDataRows());
            }

            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //待受理的申请数
    @ResponseBody
    @RequestMapping(value = {"/accepted"})
    public AjaxTableResponseMessage queryAccepted(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            Map map = new HashMap();
            map.put("id", login.getStaffId().toString());

            Map entity = easyService.queryEntity("BASE_Staff", map);
            Map paramNew = new HashMap();
            paramNew.put("orgId", login.getOrgId());
            paramNew.put("telephone", login.getcUserTelephone());
            paramNew.put("staffId", login.getStaffId().toString());
            if (entity.size() > 0) {
                paramNew.put("telephone", entity.get("telephone"));
                String role = entity.get("role").toString();
                login.setRoleId(role);
            }
            //1：超管2：中心管理3：客户管理4：使用5：维修 0:未认证
            String sql = "";
            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select count(e.id) totalNum from BUSI_MaintenanceApplication e where validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and state in ('201203','201301','201302','201502')";
            } else if (login.getRoleId().equals("3")) {
                sql = "  select count(e.id) totalNum from BUSI_MaintenanceApplication e " +
                        " left join BASE_Equipment q on e.equipmentId=q.id " +
                        "  where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and e.state in ('201201','201202')" +
                        " and  q.organizationId in(" +
                        " select id from BASE_Organization o where o.id=:orgId or o.superOrganizationId=:orgId" +
                        ")";
            } else if (login.getRoleId().equals("4") || login.getRoleId().equals("0")) {
                sql = "  select count(e.id) totalNum from BUSI_MaintenanceApplication e where validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and (applyStaffId =:staffId or telephone=:telephone)" +
                        " and state in ('201601','201602')";
            } else if (login.getRoleId().equals("5")) {
                sql = "  select count(e.id) totalNum from BUSI_MaintenanceApplication e " +
                        " where validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and (select top 1 toStaffId from BUSI_RepairSubmitRecord s where e.id=s.repairApplyId and validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' and state='" + Constains.RepairSubmit_NEW + "' order by createTime desc )=:staffId" +
                        " and state in ('201402')";
            }
            DataTable all = easyService.querySql(sql, paramNew);

            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //待受理的申请数
    @ResponseBody
    @RequestMapping(value = {"/queryMyJob"})
    public AjaxTableResponseMessage queryMyJob(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            Map map = new HashMap();
            map.put("id", login.getStaffId().toString());
            String sql = "";
            if (login.getRoleId().equals("4")) {
                sql = "  select e.*,b.name,b.oneCode eType,o.name orgName,b.usePosition,c.name questionTypeName,r.id sdId " +
                        " from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Organization o on b.organizationId =o.id " +
                        " left join  BUSI_RepairSubmitRecord r on r.repairApplyId=e.id " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' " +
                        " and e.state in (" + param.get("estate").toString() + ") " +
                        " and r.state in (" + param.get("rstate").toString() + ") " +
                        " and r.toStaffId=:id";
            } else {
                throw new Exception("您的身份不是维修人员");
            }
            DataTable all = easyService.querySql(sql, map);
            if (param.get("queryDetail") != null) {
                for (int i = 0; i < all.getDataRows().size(); i++) {
                    Map row = all.getDataRows().get(i);
                    Map temp = new HashMap();
                    temp.put("id", row.get("id").toString());
                    //获取维修附件记录
                    sql = "select r.* from BUSI_RepairSupplement r " +
                            " where r.repairApplyId=:id order by r.createTime";
                    DataTable supplement = easyService.querySql(sql, temp);
                    row.put("supplement", supplement.getDataRows());
                }
            }
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //维修中数据
    @ResponseBody
    @RequestMapping(value = {"/maintenanceList"})
    public AjaxTableResponseMessage queryMaintenanceList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            Map map = new HashMap();
            map.put("id", login.getStaffId().toString());

            Map entity = easyService.queryEntity("BASE_Staff", map);
            Map paramNew = new HashMap();
            paramNew.put("orgId", login.getOrgId());
            paramNew.put("telephone", login.getcUserTelephone());
            paramNew.put("staffId", login.getStaffId().toString());
            if (entity.size() > 0) {
                paramNew.put("telephone", entity.get("telephone"));
                String role = entity.get("role").toString();
                login.setRoleId(role);
            }
            //1：超管2：中心管理3：客户管理4：使用5：维修 0:未认证
            String sql = "";
            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select e.*,b.name,case when op.id is null then o.name else op.name+'-'+o.name end orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Organization o on b.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and e.state in ('201201','201202','201203','201301','201302','201402','201501','201502')";
            } else if (login.getRoleId().equals("3")) {
                sql = "  select e.*,b.name,op.name+'-'+o.name orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Organization o on b.organizationId =o.id left join BASE_Organization op on o.superOrganizationId=op.id " +
                        " left join BASE_Equipment q on e.equipmentId=q.id " +
                        "  where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and e.state in ('201201','201202','201203','201301','201302','201402','201501','201502')" +
                        " and  q.organizationId in(" +
                        " select id from BASE_Organization o where o.id=:orgId or o.superOrganizationId=:orgId" +
                        ")";
            } else if (login.getRoleId().equals("4") || login.getRoleId().equals("0")) {
                sql = "  select e.*,b.name,case when op.id is null then o.name else op.name+'-'+o.name end orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Organization o on b.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and (e.applyStaffId =:staffId or e.telephone=:telephone)" +
                        " and e.state in ('201201','201202','201203','201301','201302','201402','201501','201502')";
            } else if (login.getRoleId().equals("5")) {
                sql = "  select e.*,b.name,case when op.id is null then o.name else op.name+'-'+o.name end orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Organization o on b.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and (select top 1 toStaffId from BUSI_RepairSubmitRecord s where e.id=s.repairApplyId and validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' and state='" + Constains.RepairSubmit_OK + "' order by createTime desc )=:staffId" +
                        " and e.state in ('201501')";
            }
            DataTable all = easyService.querySql(sql, paramNew);
            for (int i = 0; i < all.getDataRows().size(); i++) {
                Map row = all.getDataRows().get(i);
                Map temp = new HashMap();
                temp.put("id", row.get("id").toString());
                //获取维修提交记录
                sql = "select r.*,c.name submitName,s.telephone from BUSI_RepairSubmitRecord r " +
                        "  left join BASE_Const c on c.code=r.submitType " +
                        "  left join BASE_Staff s on s.id=r.toStaffId " +
                        " where r.state='" + Constains.RepairSubmit_OK + "' and r.repairApplyId=:id order by r.createTime";
                DataTable submit = easyService.querySql(sql, temp);
                row.put("submitRecord", submit.getDataRows());

                //获取维修附件记录
                sql = "select r.* from BUSI_RepairSupplement r " +
                        " where r.repairApplyId=:id order by r.createTime";
                DataTable supplement = easyService.querySql(sql, temp);
                row.put("supplement", supplement.getDataRows());
            }

            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //待受理的申请列表
    @ResponseBody
    @RequestMapping(value = {"/acceptedList"})
    public AjaxTableResponseMessage queryAcceptedList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            Map map = new HashMap();
            map.put("id", login.getStaffId().toString());

            Map entity = easyService.queryEntity("BASE_Staff", map);
            Map paramNew = new HashMap();
            paramNew.put("orgId", login.getOrgId());
            paramNew.put("telephone", login.getcUserTelephone());
            paramNew.put("staffId", login.getStaffId().toString());
            if (entity.size() > 0) {
                paramNew.put("telephone", entity.get("telephone"));
                String role = entity.get("role").toString();
                login.setRoleId(role);
            }
            String sql = "";
            if (login.getRoleId().equals("2")) {
                sql = "  select f.name as applyName,e.*,b.name,o.name orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Staff f on f.id=e.applyStaffId" +
                        " left join  BASE_Organization o on b.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " left join BASE_Equipment q on e.equipmentId=q.id " +
                        "  where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and e.state in (" + param.get("state") + ")  order by e.createTime desc";
            } else {
                throw new Exception("无此功能的使用权限");
            }
            DataTable all = easyService.querySql(sql, paramNew);

            for (int i = 0; i < all.getDataRows().size(); i++) {
                Map row = all.getDataRows().get(i);
                Map temp = new HashMap();
                temp.put("id", row.get("id").toString());
                //获取维修提交记录
                sql = "select r.*,c.name submitName,s.telephone from BUSI_RepairSubmitRecord r " +
                        "  left join BASE_Const c on c.code=r.submitType " +
                        "  left join BASE_Staff s on s.id=r.toStaffId " +
                        " where r.state='" + Constains.RepairSubmit_OK + "' and r.repairApplyId=:id order by r.createTime";

                DataTable submit = easyService.querySql(sql, temp);
                row.put("submitRecord", submit.getDataRows());

                //获取维修附件记录
                sql = "select r.* from BUSI_RepairSupplement r " +
                        " where r.repairApplyId=:id order by r.createTime";
                DataTable supplement = easyService.querySql(sql, temp);
                row.put("supplement", supplement.getDataRows());
            }
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //审核历史记录
    @ResponseBody
    @RequestMapping(value = {"/historyCheckList"})
    public AjaxTableResponseMessage historyCheckList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            Map map = new HashMap();
            map.put("id", login.getStaffId().toString());

            Map entity = easyService.queryEntity("BASE_Staff", map);
            Map paramNew = new HashMap();
            paramNew.put("orgId", login.getOrgId());
            paramNew.put("telephone", login.getcUserTelephone());
            paramNew.put("staffId", login.getStaffId().toString());
            if (entity.size() > 0) {
                paramNew.put("telephone", entity.get("telephone"));
                String role = entity.get("role").toString();
                login.setRoleId(role);
            }
            String sql = "";
            if (login.getRoleId().equals("2")) {
                sql = "  select f.name as applyName,e.*,b.name,o.name orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Staff f on f.id=e.applyStaffId" +
                        " left join  BASE_Organization o on b.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " left join BASE_Equipment q on e.equipmentId=q.id " +
                        "  where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and e.state not in ('201101','201102','201201','201202') order by e.createTime desc";
            } else {
                throw new Exception("无此功能的使用权限");
            }
            DataTable all = easyService.querySql(sql, paramNew);

            for (int i = 0; i < all.getDataRows().size(); i++) {
                Map row = all.getDataRows().get(i);
                Map temp = new HashMap();
                temp.put("id", row.get("id").toString());
                //获取维修提交记录
                sql = "select r.*,c.name submitName,s.telephone from BUSI_RepairSubmitRecord r " +
                        "  left join BASE_Const c on c.code=r.submitType " +
                        "  left join BASE_Staff s on s.id=r.toStaffId " +
                        " where r.state='" + Constains.RepairSubmit_OK + "' and r.repairApplyId=:id order by r.createTime";

                DataTable submit = easyService.querySql(sql, temp);
                row.put("submitRecord", submit.getDataRows());

                //获取维修附件记录
                sql = "select r.* from BUSI_RepairSupplement r " +
                        " where r.repairApplyId=:id order by r.createTime";
                DataTable supplement = easyService.querySql(sql, temp);
                row.put("supplement", supplement.getDataRows());
            }
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //已结束的申请列表
    @ResponseBody
    @RequestMapping(value = {"/historyList"})
    public AjaxTableResponseMessage queryhistoryList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            Map map = new HashMap();
            map.put("id", login.getStaffId().toString());

            Map entity = easyService.queryEntity("BASE_Staff", map);
            Map paramNew = new HashMap();
            paramNew.put("orgId", login.getOrgId());
            paramNew.put("telephone", login.getcUserTelephone());
            paramNew.put("staffId", login.getStaffId().toString());
            if (entity.size() > 0) {
                paramNew.put("telephone", entity.get("telephone"));
                String role = entity.get("role").toString();
                login.setRoleId(role);
            }
            //1：超管2：中心管理3：客户管理4：使用5：维修 0:未认证
            String sql = "";
            if (login.getRoleId().equals("1") || login.getRoleId().equals("2")) {
                sql = "  select e.*,b.name,case when op.id is null then o.name else op.name+'-'+o.name end orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Organization o on b.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and e.state in ('201801','201702','201401')";
            } else if (login.getRoleId().equals("3")) {
                sql = "  select e.*,b.name,case when op.id is null then o.name else op.name+'-'+o.name end orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Organization o on b.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " left join BASE_Equipment q on e.equipmentId=q.id " +
                        "  where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and e.state in ('201303','201801','201702')" +
                        " and  q.organizationId in(" +
                        " select id from BASE_Organization o where o.id=:orgId or o.superOrganizationId=:orgId" +
                        ")";
            } else if (login.getRoleId().equals("4") || login.getRoleId().equals("0")) {
                sql = "  select e.*,b.name,case when op.id is null then o.name else op.name+'-'+o.name end orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Organization o on b.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and (e.applyStaffId =:staffId or e.telephone=:telephone)" +
                        " and e.state in ('201702','201801','201303','201401','201602')";
            } else if (login.getRoleId().equals("5")) {
                sql = "  select e.*,b.name,case when op.id is null then o.name else op.name+'-'+o.name end orgName,b.usePosition,c.name questionTypeName from BUSI_MaintenanceApplication e " +
                        " left join  BASE_Equipment b on b.id=e.equipmentId" +
                        " left join  BASE_Const c on c.code=e.questionTypeCode" +
                        " left join  BASE_Organization o on b.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                        " where e.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'" +
                        " and :staffId in (select toStaffId from BUSI_RepairSubmitRecord s where e.id=s.repairApplyId and validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' and state='" + Constains.RepairSubmit_NEW + "' )" +
                        " and e.state not in ('201402')";
            }
            DataTable all = easyService.querySql(sql, paramNew);

            for (int i = 0; i < all.getDataRows().size(); i++) {
                Map row = all.getDataRows().get(i);
                Map temp = new HashMap();
                temp.put("id", row.get("id").toString());
                //获取维修提交记录
                sql = "select r.*,c.name submitName,s.telephone from BUSI_RepairSubmitRecord r " +
                        "  left join BASE_Const c on c.code=r.submitType " +
                        "  left join BASE_Staff s on s.id=r.toStaffId " +
                        " where r.state='" + Constains.RepairSubmit_OK + "' and r.repairApplyId=:id order by r.createTime";
                DataTable submit = easyService.querySql(sql, temp);
                row.put("submitRecord", submit.getDataRows());

                //获取维修附件记录
                sql = "select r.* from BUSI_RepairSupplement r " +
                        " where r.repairApplyId=:id order by r.createTime";
                DataTable supplement = easyService.querySql(sql, temp);
                row.put("supplement", supplement.getDataRows());
            }
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/applyRepair"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage applyRepair(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, Object> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);

                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                //保存申请
                Map MaintenanceApplication = new HashMap();
                MaintenanceApplication.put("applyStaffId", login.getStaffId().toString());
                MaintenanceApplication.put("telephone", map.get("telephone"));
                MaintenanceApplication.put("openId", map.get("openId"));
                MaintenanceApplication.put("equipmentId", map.get("equipmentId").toString());
                MaintenanceApplication.put("questionTypeCode", map.get("questionTypeCode"));
                MaintenanceApplication.put("questionDescripe", map.get("questionDescripe"));
                MaintenanceApplication.put("flowCode", FlowCodeUtil.getFlowCode());
                MaintenanceApplication.put("state", Constains.STATE_SUBMIT_MESSAGE);//直接提交资产管理员
                easyService.save("BUSI_MaintenanceApplication", "id", MaintenanceApplication);
                Map message = new HashMap();
                message.put("template", Constains.MESSAGE_TEMPLATE_2);
                message.put("staffId", MaintenanceApplication.get("applyStaffId").toString());
                message.put("orgName", equipmentService.getOrgname(map.get("equipmentId").toString()));
                message.put("mFlowCode", MaintenanceApplication.get("flowCode").toString());
                message.put("eCode", map.get("code").toString());
                message.put("time", SqlTool.getNowTimeString2());
                message.put("first", "您的维修申请已提交！");
                message.put("openId", login.getcUserOpenId());
//                messageService.saveMessages(message);

                //查询此机构的管理员 id
                String sql = "select * from BASE_Staff i where i.organizationId= " +
                        "( " +
                        "select  " +
                        "case when s.id is null then o.id else s.id end as id " +
                        "  " +
                        " from Base_organization o left join BASE_Organization s on o.superOrganizationId=s.id " +
                        " where o.id = (select organizationId from BASE_Equipment where  id=:id)" +
                        " ) " +
                        " and i.role='3'";
                Map param = new HashMap();
                param.put("id", map.get("equipmentId").toString());
                DataTable staffs = easyService.querySql(sql, param);
                for (int i = 0; i < staffs.getDataRows().size(); i++) {
                    Map messageToAdmin = new HashMap();
                    messageToAdmin.put("template", Constains.MESSAGE_TEMPLATE_1);
                    messageToAdmin.put("staffId", staffs.getDataRows().get(i).get("id").toString());
                    messageToAdmin.put("orgName", message.get("orgName"));
                    Map<String, String> orgNames = equipmentService.getOrgname(map.get("equipmentId").toString());
//                    messageToAdmin.put("orgName",orgNames.get("topName"));
                    messageToAdmin.put("deptName", orgNames.get("deptName"));
                    messageToAdmin.put("name", login.getcUserName());
                    messageToAdmin.put("tel", map.get("telephone"));
                    messageToAdmin.put("type", constService.queryValue(map.get("eType").toString()));
                    messageToAdmin.put("first", "您有新的维修申请需要处理！");
                    messageToAdmin.put("mFlowCode", MaintenanceApplication.get("flowCode").toString());
                    messageToAdmin.put("eCode", map.get("code").toString());
//                    messageService.saveMessages(messageToAdmin);
                }

                //更新资产状态
                Map updateEquipment = new HashMap();
                updateEquipment.put("state", Constains.Equipment_state_Repair);
                Map queryEquipment = new HashMap();
                queryEquipment.put("id", map.get("equipmentId").toString());
                easyService.update("BASE_Equipment", queryEquipment, updateEquipment);

                //保存图片附件
                ArrayList array = (ArrayList) map.get("repairSupplement");
                if (array.size() > 0) {
                    for (int i = 0; i < array.size(); i++) {
                        Map repairSupplement = new HashMap();
                        repairSupplement.put("fileAddress", FileTools.saveImage("repairPic", array.get(i).toString()));
                        repairSupplement.put("repairApplyId", MaintenanceApplication.get("id").toString());
                        repairSupplement.put("uploadStaffId", login.getStaffId().toString());
                        repairSupplement.put("dataType", Constains.DATA_QUESTION_SUPPLEMENT);
                        easyService.save("BUSI_RepairSupplement", "id", repairSupplement);
                    }
                }

                //通知管理员模板消息


                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/applyRepairSupplement"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage applyRepairSupplement(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, Object> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);

                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));

                //保存图片附件
                ArrayList array = (ArrayList) map.get("repairSupplement");
                if (array.size() > 0) {
                    for (int i = 0; i < array.size(); i++) {
                        Map repairSupplement = new HashMap();
                        if (i == 0)
                            repairSupplement.put("fileDescribe", map.get("fileDescribe").toString());//如果有图片又有文字就夹杂到一起保存了
                        repairSupplement.put("fileAddress", FileTools.saveImage("repairPic", array.get(i).toString()));
                        repairSupplement.put("repairApplyId", map.get("id").toString());
                        repairSupplement.put("uploadStaffId", login.getStaffId().toString());
                        repairSupplement.put("dataType", Constains.DATA_QUESTION_SUPPLEMENT);
                        easyService.save("BUSI_RepairSupplement", "id", repairSupplement);
                    }
                } else {
                    if (map.get("fileDescribe") != null && !"".equals(map.get("fileDescribe"))) {
                        Map repairSupplement = new HashMap();
                        repairSupplement.put("fileDescribe", map.get("fileDescribe").toString());
                        repairSupplement.put("repairApplyId", map.get("id").toString());
                        repairSupplement.put("uploadStaffId", login.getStaffId().toString());
                        repairSupplement.put("dataType", Constains.DATA_QUESTION_SUPPLEMENT);
                        easyService.save("BUSI_RepairSupplement", "id", repairSupplement);
                    }
                }
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/checkRepair"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage checkRepair(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, Object> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);

                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));

                Map MaintenanceApplicationQuery = new HashMap();
                MaintenanceApplicationQuery.put("id", map.get("id"));
                Map MaintenanceApplicationUpdate = new HashMap();

                if (map.get("type").toString().startsWith("1")) {
                    MaintenanceApplicationUpdate.put("state", Constains.STATE_INNER_FINISH);
                } else if (map.get("type").toString().startsWith("2")) {
                    MaintenanceApplicationUpdate.put("state", Constains.STATE_MESSAGE_TO_CENTERMESSAGE);
                } else if (map.get("type").toString().startsWith("3")) {
                    MaintenanceApplicationUpdate.put("state", Constains.STATE_MESSAGE_REJECT);
                } else {
                    ajaxDataResponseMessage.setSuccess(false);
                    ajaxDataResponseMessage.setErrorMsg("请选择审核类型！");
                    return ajaxDataResponseMessage;
                }

                MaintenanceApplicationUpdate.put("questionDescripe", map.get("questionDescripe").toString());
                easyService.update("BUSI_MaintenanceApplication", MaintenanceApplicationQuery, MaintenanceApplicationUpdate);

                if (map.get("type").toString().startsWith("3") || map.get("type").toString().startsWith("1")) {
                    //资产改为正常
                    Map queryEquipment = new HashMap();
                    queryEquipment.put("id", map.get("equipmentId").toString());
                    Map updateEquipment = new HashMap();
                    updateEquipment.put("state", Constains.Equipment_state_normal);
                    easyService.update("BASE_Equipment", queryEquipment, updateEquipment);
                }

                Map MaintenanceApplication = easyService.queryEntity("BUSI_MaintenanceApplication", MaintenanceApplicationQuery);
                //通知模板消息
                if (false) {
                    if (map.get("type").toString().startsWith("1")) {
                        Map message = new HashMap();
                        message.put("template", Constains.MESSAGE_TEMPLATE_2);
                        message.put("staffId", MaintenanceApplication.get("applyStaffId").toString());
                        message.put("orgName", equipmentService.getOrgname(map.get("equipmentId").toString()));
                        message.put("mFlowCode", MaintenanceApplication.get("flowCode").toString());
                        message.put("eCode", map.get("code").toString());
                        message.put("time", SqlTool.getNowTimeString2());
                        message.put("first", "您的维修申请已处理结束！");
                        message.put("remark", map.get("questionDescripe").toString());
//                    messageService.saveMessages(message);
                    } else if (map.get("type").toString().startsWith("2")) {
                        //查询此机构的管理员 id
                        String sql = "select * from BASE_Staff i where  i.role='2'";
                        Map param = new HashMap();
                        param.put("id", map.get("equipmentId").toString());
                        DataTable staffs = easyService.querySql(sql, param);
                        for (int i = 0; i < staffs.getDataRows().size(); i++) {
                            Map messageToAdmin = new HashMap();
                            messageToAdmin.put("template", Constains.MESSAGE_TEMPLATE_1);
                            messageToAdmin.put("staffId", staffs.getDataRows().get(i).get("id").toString());
                            Map<String, String> orgNames = equipmentService.getOrgname(map.get("equipmentId").toString());
                            messageToAdmin.put("orgName", orgNames.get("topName"));
                            messageToAdmin.put("deptName", orgNames.get("deptName"));
                            messageToAdmin.put("name", map.get("staffName"));
                            messageToAdmin.put("tel", map.get("telephone"));
                            messageToAdmin.put("type", constService.queryValue(map.get("eType").toString()));
                            messageToAdmin.put("first", "您有新的维修申请需要处理！");
//                        messageService.saveMessages(messageToAdmin);
                        }
                    } else if (map.get("type").toString().startsWith("3")) {
                        Map message = new HashMap();
                        message.put("template", Constains.MESSAGE_TEMPLATE_2);
                        message.put("staffId", MaintenanceApplication.get("applyStaffId").toString());
                        message.put("orgName", equipmentService.getOrgname(map.get("equipmentId").toString()));
                        message.put("mFlowCode", MaintenanceApplication.get("flowCode").toString());
                        message.put("eCode", map.get("code").toString());
                        message.put("time", SqlTool.getNowTimeString2());
                        message.put("first", "您的维修申请已被驳回！");
                        message.put("remark", map.get("questionDescripe").toString());
//                    messageService.saveMessages(message);
                    }
                }
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }


    @ResponseBody
    @RequestMapping(value = {"/updateRepairState"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage updateRepairState(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, Object> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);

                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));

                Map MaintenanceApplicationQuery = new HashMap();
                MaintenanceApplicationQuery.put("id", map.get("id"));
                Map MaintenanceApplicationUpdate = new HashMap();

                if (map.get("state") != null && map.get("state").toString().equals(Constains.STATE_END_WORK)) {
                    MaintenanceApplicationUpdate.put("state", Constains.STATE_END_WORK);
                    easyService.update("BUSI_MaintenanceApplication", MaintenanceApplicationQuery, MaintenanceApplicationUpdate);
                    //资产改为正常
                    Map queryEquipment = new HashMap();
                    queryEquipment.put("id", map.get("equipmentId"));
                    Map updateEquipment = new HashMap();
                    updateEquipment.put("state", Constains.Equipment_state_normal);
                    easyService.update("BASE_Equipment", queryEquipment, updateEquipment);
                }

                if (map.get("validFlag") != null && map.get("validFlag").toString().equals(Constains.SYS_VALIDFLAG_FALSE)) {
                    MaintenanceApplicationUpdate.put("validFlag", Constains.SYS_VALIDFLAG_FALSE);
                    easyService.update("BUSI_MaintenanceApplication", MaintenanceApplicationQuery, MaintenanceApplicationUpdate);
                }
                //通知模板消息


                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    //接单结果
    @ResponseBody
    @RequestMapping(value = {"/updateRepairWorkState"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage updateRepairWorkState(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, Object> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);

                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));

                Map MaintenanceApplicationQuery = new HashMap();
                MaintenanceApplicationQuery.put("id", map.get("repairApplyId").toString());
                Map MaintenanceApplicationUpdate = new HashMap();
                MaintenanceApplicationUpdate.put("state", map.get("repairApplyState"));
                easyService.update("BUSI_MaintenanceApplication", MaintenanceApplicationQuery, MaintenanceApplicationUpdate);

                Map RepairSubmitRecordQuery = new HashMap();
                RepairSubmitRecordQuery.put("id", map.get("id").toString());
                Map MRepairSubmitRecordUpdate = new HashMap();
                MRepairSubmitRecordUpdate.put("state", map.get("state"));
                easyService.update("BUSI_RepairSubmitRecord", RepairSubmitRecordQuery, MRepairSubmitRecordUpdate);

                Map MaintenanceApplication = easyService.queryEntity("BUSI_MaintenanceApplication", MaintenanceApplicationQuery);
                //通知模板消息
                if (Constains.RepairSubmit_OK.equals(map.get("state").toString())) {
                    //接受 通知申请人 通知中心
                    if (MaintenanceApplication.get("applyStaffId") == null || "".equals(MaintenanceApplication.get("applyStaffId"))) {
                        //后台申请是无法通知的
                    } else {
                        Map message = new HashMap();
                        message.put("template", Constains.MESSAGE_TEMPLATE_5);
                        message.put("staffId", MaintenanceApplication.get("applyStaffId").toString());
                        message.put("mFlowCode", MaintenanceApplication.get("flowCode").toString());
                        message.put("name", login.getcUserName());
                        message.put("tel", login.getcUserTelephone());
                        message.put("time", SqlTool.getNowTimeString2());
                        message.put("first", "已派单！");
                        messageService.saveMessages(message);
                    }
                    //查询此机构的管理员 id
                    String sql = "select * from BASE_Staff i where i.role='2'";
                    Map param = new HashMap();
                    DataTable staffs = easyService.querySql(sql, param);
                    for (int i = 0; i < staffs.getDataRows().size(); i++) {
                        Map messageToAdmin = new HashMap();
                        messageToAdmin.put("template", Constains.MESSAGE_TEMPLATE_5);
                        messageToAdmin.put("staffId", staffs.getDataRows().get(i).get("id").toString());
                        messageToAdmin.put("mFlowCode", MaintenanceApplication.get("flowCode").toString());
                        messageToAdmin.put("orgName", equipmentService.getOrgname(MaintenanceApplication.get("equipmentId").toString()));
                        messageToAdmin.put("name", login.getcUserName());
                        messageToAdmin.put("tel", login.getcUserTelephone());
                        List typeList = easyService.querySql("select * from base_eqClass where code='" + map.get("eType").toString() + "'", new HashMap<>()).getDataRows();
                        if (typeList.size() >= 0) {
                            messageToAdmin.put("type", ((Map) typeList.get(0)).get("name").toString());
                        } else {
                            messageToAdmin.put("type", "其他");
                        }
                        messageToAdmin.put("first", "已接单！");
                        messageService.saveMessages(messageToAdmin);
                    }

                } else {
                    //驳回 通知中心
                    Map message = new HashMap();
                    message.put("template", Constains.MESSAGE_TEMPLATE_5);
                    message.put("staffId", RepairSubmitRecordQuery.get("fromStaffId").toString());
                    message.put("mFlowCode", MaintenanceApplication.get("flowCode").toString());
                    message.put("name", login.getcUserName());
                    message.put("tel", login.getcUserTelephone());
                    message.put("time", SqlTool.getNowTimeString2());
                    message.put("first", "接单失败");
                    messageService.saveMessages(message);
                }
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    //维修结果
    @ResponseBody
    @RequestMapping(value = {"/saveRepairWorkResult"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage saveRepairWorkResult(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, Object> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);

                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));

                Map MaintenanceApplicationQuery = new HashMap();
                MaintenanceApplicationQuery.put("id", map.get("repairApplyId").toString());
                Map MaintenanceApplicationUpdate = new HashMap();
                MaintenanceApplicationUpdate.put("state", map.get("repairApplyState"));
                MaintenanceApplicationUpdate.put("maintenanceResult", map.get("result").toString());
                MaintenanceApplicationUpdate.put("maintenanceTime", SqlTool.getNowTimeString());
                MaintenanceApplicationUpdate.put("maintenanceStaffId", login.getStaffId().toString());
                MaintenanceApplicationUpdate.put("maintenanceDescribe", map.get("describe").toString());

                easyService.update("BUSI_MaintenanceApplication", MaintenanceApplicationQuery, MaintenanceApplicationUpdate);

                //资产状态改为运行中，不管修失败了还是成功了
                Map eQuery = new HashMap();
                eQuery.put("id", map.get("equipmentId").toString());
                Map eUpdate = new HashMap();
                eUpdate.put("state", Constains.Equipment_state_normal);
                easyService.update("BASE_Equipment", eQuery, eUpdate);

//                //插入维修结果数据
//                Map entity=new HashMap();
//                entity.put("equipmentId",map.get("equipmentId").toString());
//                entity.put("maintenanceResult",map.get("result").toString());
//                entity.put("maintenanceTime", SqlTool.getNowTimeString());
//                entity.put("maintenanceStaffId",login.getStaffId().toString());
//                entity.put("state","200001");
//                easyService.save("BUSI_handleResult", "id", entity);

                //通知模板消息
                Map MaintenanceApplication = easyService.queryEntity("BUSI_MaintenanceApplication", MaintenanceApplicationQuery);
                if (MaintenanceApplication.get("applyStaffId") == null || "".equals(MaintenanceApplication.get("applyStaffId"))) {
                    //后台申请是无法通知的
                } else {
                    Map message = new HashMap();
                    message.put("template", Constains.MESSAGE_TEMPLATE_4);
                    message.put("staffId", MaintenanceApplication.get("applyStaffId").toString());
                    message.put("result", constService.queryValue(map.get("repairApplyState").toString()) + " " + map.get("result").toString());
                    message.put("name", login.getcUserName());
                    message.put("tel", login.getcUserTelephone());
                    message.put("time", SqlTool.getNowTimeString2());
                    message.put("first", "您的资产维修已完成！");
                    message.put("remark", "维修单号：" + MaintenanceApplication.get("flowCode").toString());
                    message.put("eCode", "");
                    message.put("mFlowCode", MaintenanceApplication.get("flowCode").toString());
                    messageService.saveMessages(message);
                }
                //查询此机构的管理员 id
                String sql = "select * from BASE_Staff i where  i.role='2'";
                Map param = new HashMap();
                param.put("id", map.get("equipmentId").toString());
                DataTable staffs = easyService.querySql(sql, param);
                for (int i = 0; i < staffs.getDataRows().size(); i++) {
                    Map messageToAdmin = new HashMap();
                    messageToAdmin.put("template", Constains.MESSAGE_TEMPLATE_4);
                    messageToAdmin.put("staffId", staffs.getDataRows().get(i).get("id").toString());
                    messageToAdmin.put("result", constService.queryValue(map.get("repairApplyState").toString()));
                    messageToAdmin.put("name", login.getcUserName());
                    messageToAdmin.put("tel", login.getcUserTelephone());
                    messageToAdmin.put("time", SqlTool.getNowTimeString2());
                    messageToAdmin.put("first", "资产维修已完成！");
                    messageToAdmin.put("remark", "维修单号：" + MaintenanceApplication.get("flowCode").toString());
                    messageToAdmin.put("eCode", "");
                    messageToAdmin.put("mFlowCode", MaintenanceApplication.get("flowCode").toString());
                    messageService.saveMessages(messageToAdmin);
                }

                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);

            logger.error("系统异常", e);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/indexIs"})
    public AjaxTableResponseMessage indexIs(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                String sql = "SELECT  c.name,p.typeCode,p.picture1,p.picture2,p.picture3,p.picture4," +
                        " p.picture5,p.picture6,p.indexState,p.describe,p.code FROM BASE_Product p " +
                        " left join BASE_Const c on c.code=p.typeCode" +
                        "  where p.validFlag='100001' and p.productState='" + Constains.PRODUCT_SHOW_TRUE + "' and  p.indexState='" + Constains.INDEX_TRUE + "'" +
                        "  order by p.createTime desc";
                DataTable all = easyService.querySql(sql, map);
                ajaxTableResponseMessage.setDatas(all.getDataRows());
                ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
                ajaxTableResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/indexIsNot"})
    public AjaxTableResponseMessage indexIsNot(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                String sql = "SELECT  c.name,p.typeCode,p.picture1,p.picture2,p.picture3,p.picture4," +
                        "p.picture5,p.picture6,p.indexState,p.describe,p.code FROM BASE_Product p " +
                        "left join BASE_Const c on c.code=p.typeCode " +
                        " where p.validFlag='100001' and p.productState='" + Constains.PRODUCT_SHOW_TRUE + "'" +
                        " order by p.typeCode, p.indexState,p.createTime desc";
                DataTable all = easyService.querySql(sql, map);
                ajaxTableResponseMessage.setDatas(all.getDataRows());
                ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
                ajaxTableResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/groupType"})
    public AjaxTableResponseMessage groupType(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                String sql = "SELECT c.name,count(p.id) count FROM BASE_Product p " +
                        " left join BASE_Const c on c.code=p.typeCode" +
                        " group by c.name";
                DataTable all = easyService.querySql(sql, map);
                ajaxTableResponseMessage.setDatas(all.getDataRows());
                ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
                ajaxTableResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }


    @ResponseBody
    @RequestMapping(value = {"/searchEquipment"})
    public AjaxTableResponseMessage searchEquipment(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                Map param = new HashMap();
                param.put("orgId", login.getOrgId());
                param.put("superOrganizationId", login.getOrgId());
                param.put("organizationType", "400001");
                Map myOrg = constService.queryMyOrg(param);
                param = searchService.searchParamBuild(map.get("keyWord"), myOrg.get("allorgs").toString());
                String sql = "select * from View_Equipment where 1=1 " +
                        (param.get("equipmentOneCode") == null ? "" : " and oneCode in (" + param.get("equipmentOneCode") + ") ") +
                        (param.get("equipmentState") == null ? "" : " and state in (" + param.get("equipmentState") + ") ") +
                        (param.get("equipmentBrand") == null ? "" : " and brandCode in (" + param.get("equipmentBrand") + ") ") +
                        (param.get("useType") == null ? "" : " and useType in (" + param.get("useType") + ") ") +
                        (param.get("dept") == null ? "" : " and useOrgId in (" + param.get("dept") + ") ") +
                        (param.get("staff") == null ? "" : " and useStaffId in (" + param.get("staff") + ") ") +
                        (param.get("QRCode") == null ? "" : " and QRCode in (" + param.get("QRCode") + ") ") +
                        (param.get("model") == null ? "" : " and model like '%'+" + param.get("model") + "+'%' ") +
                        (param.get("useDate") == null ? "" : " and wcUTime >= ('" + param.get("useDate") + " 0:0:0')  and wcUTime <= ('" + param.get("useDate") + " 23:59:59') ");
                if (sql.equals("select * from View_Equipment where 1=1 ")) {
                    sql = "select 0 where 1=2";
                }
                DataTable all = easyService.querySql(sql, param);
                ajaxTableResponseMessage.setDatas(all.getDataRows());
                ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
                ajaxTableResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/searchOrgStaff"})
    public AjaxTableResponseMessage searchOrgStaff(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                Map param = new HashMap();
                param.put("orgId", login.getOrgId());
                param.put("superOrganizationId", login.getOrgId());
                param.put("organizationType", "400001");
                Map myOrg = constService.queryMyOrg(param);
                param = searchService.searchParamBuild(map.get("keyWord"), myOrg.get("allorgs").toString());
                String sql = "SELECT r.cRoleName roleName,s.* from base_staff s left join PM_ROLES r on s.role=r.cRoleID where s.validFlag='100001' and s.organizationId in (" + myOrg.get("allorgs").toString() + ")" +
                        (param.get("dept") == null ? "" : " and organizationId in (" + param.get("dept") + ") ") +
                        (param.get("staff") == null ? "" : " and id in (" + param.get("staff") + ") ");
                if (param.get("dept") == null && param.get("staff") == null) {
                    sql = "select 0 where 1=2";
                }
                DataTable all = easyService.querySql(sql, param);
                ajaxTableResponseMessage.setDatas(all.getDataRows());
                ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
                ajaxTableResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/searchWarehouse"})
    public AjaxTableResponseMessage searchWarehouse(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                //判断session的权限，超管可以查看所有仓库，库管只能查询绑定关系的仓库
                String where = "";
                switch (login.getRoleId()) {
                    case "1":
                        where = " and 1=1 ";
                        break;
                    case "2"://
                        where = " and 1=1 ";
                        break;
                    case "3"://
                        where = " and w.id in (select warehouseId from BASE_WarehouseStaff where validFlag='100001' and staffId= " + login.getStaffId() + ") ";
                        break;
                }
                Map param = new HashMap();
                param.put("orgId", login.getOrgId());
                param.put("superOrganizationId", login.getOrgId());
                param.put("organizationType", "400001");
                Map myOrg = constService.queryMyOrg(param);
                param = searchService.searchParamBuild(map.get("keyWord"), myOrg.get("allorgs").toString());
                String sql = "select 0 where 1=2";
                if (param.get("equipmentBrand") != null || param.get("modelCode") != null) {
                    //一个具体的型号 那么就返回型号明细
                    sql = "select * from View_WarehouseDetail w where 1=1 " +
                            (param.get("equipmentBrand") == null ? "" : " and brandCode in (" + param.get("equipmentBrand") + ") ") +
                            (param.get("equipmentOneCode") == null ? "" : " and eqCode in (" + param.get("equipmentOneCode") + ") ") +
                            (param.get("modelCode") == null ? "" : " and eId in (" + param.get("modelCode") + ") ") + where;
                } else if (param.get("equipmentOneCode") != null)
                    sql = "select * from View_WarehouseType w where 1=1 " +
                            (param.get("equipmentOneCode") == null ? "" : " and eqCode in (" + param.get("equipmentOneCode") + ") ") + where;
                DataTable all = easyService.querySql(sql, param);
                ajaxTableResponseMessage.setDatas(all.getDataRows());
                ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
                ajaxTableResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/searchWarehouseChange"})
    public AjaxTableResponseMessage searchWarehouseChange(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                //判断session的权限，超管可以查看所有仓库，库管只能查询绑定关系的仓库
                String where = "";
                switch (login.getRoleId()) {
                    case "1":
                        where = " and 1=1 ";
                        break;
                    case "2"://
                        where = " and 1=1 ";
                        break;
                    case "3"://
                        where = " and w.wId in (select warehouseId from BASE_WarehouseStaff where validFlag='100001' and staffId= " + login.getStaffId() + ") ";
                        break;
                }
                Map param = new HashMap();
                param.put("orgId", login.getOrgId());
                param.put("superOrganizationId", login.getOrgId());
                param.put("organizationType", "400001");
                Map myOrg = constService.queryMyOrg(param);
                param = searchService.searchParamBuild(map.get("keyWord"), myOrg.get("allorgs").toString());
                String sql = "select * from View_WarehouseChange w where 1=1 " +
                        (param.get("equipmentBrand") == null ? "" : " and brandCode in (" + param.get("equipmentBrand") + ") ") +
                        (param.get("equipmentOneCode") == null ? "" : " and eqCode in (" + param.get("equipmentOneCode") + ") ") +
                        (param.get("changeFlowCode") == null ? "" : " and id in (" + param.get("changeFlowCode") + ") ") +
                        (param.get("getFlowCode") == null ? "" : " and gId in (" + param.get("getFlowCode") + ") ") +
                        (param.get("useDate") == null ? "" : " and updateTime >='" + param.get("useDate") + " 0:0:0' and updateTime<='" + param.get("useDate") + " 23:59:59'") +
                        (param.get("modelCode") == null ? "" : " and modelId in (" + param.get("modelCode") + ") ");
                if (sql.equals("select * from View_WarehouseChange w where 1=1 "))
                    sql = "select 0 where 1=2";
                else sql = sql + where;
                DataTable all = easyService.querySql(sql, param);
                ajaxTableResponseMessage.setDatas(all.getDataRows());
                ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
                ajaxTableResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }
}

